import { NotFound, BadRequest } from 'http-errors'
import Brand from '@/database/models/brand'

const getBrands = async (query: Query) => {
  const pageNum = Math.abs(Number(query.pageNum)) || 1
  const pageSize = Math.abs(Number(query.pageSize)) || 10
  const offset = (pageNum - 1) * pageSize
  const { rows, count } = await Brand.findAndCountAll({
    order: [['id', 'DESC']],
    limit: pageSize,
    offset,
  })

  return {
    brands: rows,
    pagination: {
      total: count,
      pageNum,
      pageSize,
    },
  }
}

const addBrand = async (body: Body) => {
  const { brandName, brandLogo } = body
  const brand = await Brand.create({
    brandName,
    brandLogo,
  })
  return brand
}

const getBrandInfo = async (id: number) => {
  const brand = await getBrand(id)
  return brand
}

const updateBrand = async (id: number, body: Body) => {
  const { brandName, brandLogo } = body
  const brand = await getBrand(id)
  await brand!.update({
    brandName,
    brandLogo,
  })
}

const deleteBrand = async (id: number) => {
  const brand = await getBrand(id)
  await brand!.destroy()
}

/**
 * 公共方法：查询当前品牌
 * @param {number} id
 */
async function getBrand(id: number) {
  const brand = await Brand.findByPk(id)
  if (!brand) {
    throw new NotFound(`ID:${id}的品牌未找到。`)
  }
  return brand
}

export default {
  getBrands,
  addBrand,
  getBrandInfo,
  updateBrand,
  deleteBrand,
}
